<!DOCTYPE html>
<html>
<head>
    <title>库存管理系统 - SignalR 实时监控</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .card { border: 1px solid #ddd; margin: 10px; padding: 15px; border-radius: 5px; }
        .alert { padding: 10px; margin: 5px 0; border-radius: 3px; }
        .alert-warning { background-color: #fff3cd; border: 1px solid #ffeaa7; }
        .alert-error { background-color: #f8d7da; border: 1px solid #f5c6cb; }
        .alert-success { background-color: #d4edda; border: 1px solid #c3e6cb; }
        .btn { padding: 8px 16px; margin: 5px; border: none; border-radius: 3px; cursor: pointer; }
        .btn-primary { background-color: #007bff; color: white; }
        .btn-success { background-color: #28a745; color: white; }
        .btn-warning { background-color: #ffc107; color: black; }
        .status { font-weight: bold; }
        .connected { color: green; }
        .disconnected { color: red; }
        .data-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .chart-container { height: 300px; overflow-y: auto; }
        .ranking-item { padding: 5px; border-bottom: 1px solid #eee; }
        .alert-item { margin: 5px 0; padding: 8px; border-left: 4px solid #ffc107; background-color: #fff3cd; }
    </style>
</head>
<body>
    <div class="container">
        <h1>库存管理系统 - 实时监控</h1>
        
        <!-- 连接状态 -->
        <div class="card">
            <h3>SignalR 连接状态</h3>
            <p>状态: <span id="connectionStatus" class="status disconnected">未连接</span></p>
            <button id="connectBtn" class="btn btn-primary">连接</button>
            <button id="disconnectBtn" class="btn btn-warning">断开连接</button>
        </div>

        <!-- 操作区域 -->
        <div class="card">
            <h3>操作区域</h3>
            <button onclick="getInventoryRatio()" class="btn btn-primary">获取库存数量占比</button>
            <button onclick="getAmountRatio()" class="btn btn-primary">获取库存金额占比</button>
            <button onclick="getInboundRanking()" class="btn btn-primary">获取入库排名</button>
            <button onclick="getOutboundRanking()" class="btn btn-primary">获取出库排名</button>
            <button onclick="getLowStockAlert()" class="btn btn-warning">检查库存预警</button>
            <button onclick="getDashboardData()" class="btn btn-success">获取仪表板数据</button>
        </div>

        <!-- 数据展示区域 -->
        <div class="data-grid">
            <!-- 库存占比 -->
            <div class="card">
                <h3>库存数量占比</h3>
                <div id="inventoryRatio" class="chart-container">暂无数据</div>
            </div>

            <!-- 金额占比 -->
            <div class="card">
                <h3>库存金额占比</h3>
                <div id="amountRatio" class="chart-container">暂无数据</div>
            </div>

            <!-- 入库排名 -->
            <div class="card">
                <h3>入库排名</h3>
                <div id="inboundRanking" class="chart-container">暂无数据</div>
            </div>

            <!-- 出库排名 -->
            <div class="card">
                <h3>出库排名</h3>
                <div id="outboundRanking" class="chart-container">暂无数据</div>
            </div>
        </div>

        <!-- 库存预警 -->
        <div class="card">
            <h3>库存预警</h3>
            <div id="stockAlerts">暂无预警</div>
        </div>

        <!-- 系统消息 -->
        <div class="card">
            <h3>系统消息</h3>
            <div id="systemMessages"></div>
        </div>
    </div>

    <script src="https://unpkg.com/@microsoft/signalr@latest/dist/browser/signalr.js"></script>
    <script>
        const apiBase = 'http://localhost:5000/api'; // 根据实际API地址调整
        let connection = null;

        // 初始化SignalR连接
        function initSignalR() {
            connection = new signalR.HubConnectionBuilder()
                .withUrl("/inventoryReadHub")
                .build();

            // 连接事件
            connection.onclose(() => {
                updateConnectionStatus(false);
            });

            // 监听各种事件
            setupEventListeners();
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 库存数量占比
            connection.on("ReceiveInventoryQuantityRatio", function (data) {
                console.log("收到库存数量占比数据:", data);
                displayInventoryRatio(data);
            });

            // 库存金额占比
            connection.on("ReceiveInventoryAmountRatio", function (data) {
                console.log("收到库存金额占比数据:", data);
                displayAmountRatio(data);
            });

            // 出入库排名
            connection.on("ReceiveInOutboundRanking", function (data) {
                console.log("收到出入库排名数据:", data);
                displayRanking(data);
            });

            // 库存预警
            connection.on("ReceiveLowStockAlert", function (data) {
                console.log("收到库存预警:", data);
                displayStockAlerts(data);
            });

            // 入库成功消息
            connection.on("ReceiveInboundSuccess", function (data) {
                console.log("入库成功:", data);
                addSystemMessage(data, 'success');
            });

            // 出库成功消息
            connection.on("ReceiveOutboundSuccess", function (data) {
                console.log("出库成功:", data);
                addSystemMessage(data, 'success');
            });

            // 仪表板数据
            connection.on("ReceiveDashboardData", function (data) {
                console.log("收到仪表板数据:", data);
                displayDashboardData(data);
            });

            // 系统消息
            connection.on("ReceiveSystemMessage", function (data) {
                console.log("收到系统消息:", data);
                addSystemMessage(data, data.level || 'info');
            });
        }

        // 连接SignalR
        function connectSignalR() {
            if (connection) {
                connection.start().then(function () {
                    updateConnectionStatus(true);
                    console.log("SignalR连接成功");
                }).catch(function (err) {
                    console.error("SignalR连接失败:", err);
                    updateConnectionStatus(false);
                });
            }
        }

        // 断开连接
        function disconnectSignalR() {
            if (connection) {
                connection.stop();
                updateConnectionStatus(false);
            }
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusElement = document.getElementById('connectionStatus');
            if (connected) {
                statusElement.textContent = '已连接';
                statusElement.className = 'status connected';
            } else {
                statusElement.textContent = '未连接';
                statusElement.className = 'status disconnected';
            }
        }

        // API调用函数
        async function getInventoryRatio() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetGoodsPercentageNumber`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayInventoryRatio(data.data);
                }
            } catch (error) {
                console.error('获取库存占比失败:', error);
            }
        }

        async function getAmountRatio() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetInventoryAmountRatio`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayAmountRatio(data.data);
                }
            } catch (error) {
                console.error('获取金额占比失败:', error);
            }
        }

        async function getInboundRanking() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetInOutboundRanking?isInbound=true`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayRanking(data.data);
                }
            } catch (error) {
                console.error('获取入库排名失败:', error);
            }
        }

        async function getOutboundRanking() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetInOutboundRanking?isInbound=false`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayRanking(data.data);
                }
            } catch (error) {
                console.error('获取出库排名失败:', error);
            }
        }

        async function getLowStockAlert() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetLowStockAlert`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayStockAlerts(data.data);
                }
            } catch (error) {
                console.error('获取库存预警失败:', error);
            }
        }

        async function getDashboardData() {
            try {
                const response = await fetch(`${apiBase}/Statistics/GetDashboardData`);
                const data = await response.json();
                if (data.code === 'ok') {
                    displayDashboardData(data.data);
                }
            } catch (error) {
                console.error('获取仪表板数据失败:', error);
            }
        }

        // 显示函数
        function displayInventoryRatio(data) {
            const container = document.getElementById('inventoryRatio');
            if (data && data.showGoods && data.showGoods.length > 0) {
                container.innerHTML = data.showGoods.map(item => 
                    `<div class="ranking-item">
                        <strong>${item.goodsName}</strong>: ${item.percentage}%
                    </div>`
                ).join('');
            } else {
                container.innerHTML = '暂无数据';
            }
        }

        function displayAmountRatio(data) {
            const container = document.getElementById('amountRatio');
            if (data && data.goodsAmountRatios && data.goodsAmountRatios.length > 0) {
                container.innerHTML = data.goodsAmountRatios.map(item => 
                    `<div class="ranking-item">
                        <strong>${item.goodsName}</strong>: ¥${item.totalAmount.toFixed(2)} (${item.amountPercentage}%)
                    </div>`
                ).join('');
            } else {
                container.innerHTML = '暂无数据';
            }
        }

        function displayRanking(data) {
            const containerId = data.statisticsType === '入库排名' ? 'inboundRanking' : 'outboundRanking';
            const container = document.getElementById(containerId);
            if (data && data.rankings && data.rankings.length > 0) {
                container.innerHTML = data.rankings.map(item => 
                    `<div class="ranking-item">
                        第${item.rank}名: <strong>${item.goodsName}</strong> - ${item.totalQuantity}件 (${item.operationCount}次操作)
                    </div>`
                ).join('');
            } else {
                container.innerHTML = '暂无数据';
            }
        }

        function displayStockAlerts(data) {
            const container = document.getElementById('stockAlerts');
            if (data && data.lowStockItems && data.lowStockItems.length > 0) {
                container.innerHTML = data.lowStockItems.map(item => 
                    `<div class="alert-item">
                        <strong>${item.goodsName}</strong> (${item.goodsNumber})<br>
                        当前库存: ${item.currentStock}, 最低库存: ${item.minStockLevel}<br>
                        预警: ${item.alertDescription}
                    </div>`
                ).join('');
            } else {
                container.innerHTML = '暂无预警';
            }
        }

        function displayDashboardData(data) {
            if (data.inventoryQuantityRatio) {
                displayInventoryRatio(data.inventoryQuantityRatio);
            }
            if (data.inventoryAmountRatio) {
                displayAmountRatio(data.inventoryAmountRatio);
            }
            if (data.inboundRanking) {
                displayRanking(data.inboundRanking);
            }
            if (data.outboundRanking) {
                displayRanking(data.outboundRanking);
            }
            if (data.lowStockAlert) {
                displayStockAlerts(data.lowStockAlert);
            }
        }

        function addSystemMessage(data, level) {
            const container = document.getElementById('systemMessages');
            const alertClass = `alert-${level}`;
            const messageHtml = `
                <div class="alert ${alertClass}">
                    <strong>${data.title}</strong><br>
                    ${data.content}<br>
                    <small>${new Date(data.messageTime).toLocaleString()}</small>
                </div>
            `;
            container.insertAdjacentHTML('afterbegin', messageHtml);
            
            // 限制消息数量
            const messages = container.children;
            if (messages.length > 10) {
                container.removeChild(messages[messages.length - 1]);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initSignalR();
            
            // 绑定按钮事件
            document.getElementById('connectBtn').addEventListener('click', connectSignalR);
            document.getElementById('disconnectBtn').addEventListener('click', disconnectSignalR);
        });
    </script>
</body>
</html>